<?php
class p_cast extends Model{
	public static function getTableName(){
		return 'p_cast';
	}

	public function set($object)
	{
		$this->ades_id= !isset($object->ades_id) ? '0' : $object->ades_id;
		$this->programme_id= !isset($object->programme_id) ? '0' : $object->programme_id;
		$this->cast_role_id= !isset($object->cast_role_id) ? '0' : $object->cast_role_id;
		$this->gender= !isset($object->gender) ? '' : $object->gender;
		$this->age= !isset($object->age) ? '' : trim($object->age);
		$this->available_tag_types= !isset($object->available_tag_types) ? '' : $object->available_tag_types;
		$this->tags= !isset($object->tags) ? '' : $object->tags;
		$this->blog_url= !isset($object->blog_url) ? '' : trim($object->blog_url);
		$this->folders= !isset($object->folders) ? '' : $object->folders;
		$this->status= !isset($object->status) ? '0' : $object->status;
		$this->created_at= !isset($object->created_at) ? '' : $object->created_at;
		$this->created_by= !isset($object->created_by) ? '' : $object->created_by;
		$this->modified_at= !isset($object->modified_at) ? '' : $object->modified_at;
		$this->modified_by= !isset($object->modified_by) ? '' : $object->modified_by;
	}

    public function initLanguage($cast_id,$lang_id)
    {
       return $init_language = array(
            'cast_id' => $cast_id,
            'language_id' => $lang_id,
            'real_first_name' => '',
            'real_last_name'=> '',
            'first_name'=> '',
            'last_name'=>'',
            'other_name'=> '',
            'nickname'=>'',
            'occupation'=>'',
            'personality'=>'',
            'profile'=>'',
            'history'=>''
        );
    }
	public function getDetails($cast_id)
	{
		$sql = "select a.*,b.*,c.system_label from ".self::getTableName()." a left join `p_cast-language` b on a.id=b.cast_id left join cast_role c on a.cast_role_id=c.id where a.id='{$cast_id}'";
		$ret = Model::$dbo['r']->findBySql(__class__, $sql);
		
		$sql = "SELECT * FROM `p_cast-language` WHERE `cast_id` = " . $cast_id;
		$ro = Model::$dbo['r']->findBySql(__class__, $sql);
        $cast_language = array();
		foreach ($ro as $obj) {
            $array = Model::object2array($obj);
			$cast_language[$obj->language_id] = $array;
		}
     
        if( !array_key_exists('1',$cast_language) )
        {
            $init_language =  $this->initLanguage($cast_id,'1');
            $cast_language[1]= $init_language;
        }
		if( !array_key_exists('2',$cast_language) )
        {
            $init_language =  $this->initLanguage($cast_id,'2');
            $cast_language[2]= $init_language;
        }
	
		$ret[0]->cast_language = $cast_language;
		return isset($ret[0]) ? $ret[0] : "";
	}

	public function getList()
	{
		$sql = "select * from ".self::getTableName()." a left join `p_cast-language` b on a.id=b.cast_id";
		return Model::$dbo['r']->findBySql(__class__, $sql);
	}

	public function findByInSql($instr, $programme_id, $lang_id)
	{
		$instr = is_null($instr) ? '' : $instr;
		$sql = "select * from cast_role a left join p_cast b on b.cast_role_id=a.id left join `p_cast-language` c on b.id=c.cast_id where a.id in ({$instr}) and programme_id='{$programme_id}' and language_id='{$lang_id}'";
		return Model::$dbo['r']->findBySql(__class__, $sql);
	}

	public function getResultList($findRelation, $field, $operation, $value, $start, $length, $sidx	= NULL, $sord = NULL, $unpublish = 0)
	{
		$find	=	$findRelation['mapField'];
		$db_con = ($unpublish == 1) ? CommonUtils::getDbConn(0,'preview') : Model::$dbo['r'];
        # first, deal with title party!
        $titleWhere =   $programmeTitleIds  =   NULL;
        $pathWhere  =   NULL;
		$nameWhere  =   NULL;
        $searchSing =   FALSE;
        $nameSearchSing =   FALSE;
        $programmes =   array();
		$casts      =   array();
		$where      =   array();
        $resField   =   $resOperation   =   $resValue   =   array();
        $zhLanguageID = language::getLanguageID(AC::LANGUAGE_ZH);
        $enLanguageID = language::getLanguageID(AC::LANGUAGE_EN);
        foreach ($field as  $fieldKey   =>  $fieldValue)
        {
            if ('title' ==  $fieldValue)
            {
                $titleWhere[]   =   Model::assembleWhereSentence($find, $fieldValue, $operation[$fieldKey], $value[$fieldKey]);
            }
            elseif ('path'  ==  $fieldValue)
            {
                $pathWhere[]    =   Model::assembleWhereSentence($find, $fieldValue, $operation[$fieldKey], $value[$fieldKey]);
            }
			elseif ('name'  == substr($fieldValue,-4)){
				$nameSearchSing = TRUE;
				$nameWhereString =  Model::assembleWhereSentence($find, $fieldValue, $operation[$fieldKey], $value[$fieldKey]);
				$nameWhereString = str_replace('`findApi`.','',$nameWhereString);
				if($nameWhereString){
					$cast_result = CommonUtils::getCastIdsByName($fieldValue,$nameWhereString,$field,$operation,$zhLanguageID,$enLanguageID);
					if($cast_result){
						$casts[] = $cast_result;
					}
				}
            }
            elseif( 'premium' ==$fieldValue)
            {
                $resField[$fieldKey] = $fieldValue;
                $resOperation[$fieldKey] = $operation[$fieldKey];
                $resValue[$fieldKey] = 1;
            }
            else
            {
                $resField[$fieldKey]    =   $fieldValue;
                $resOperation[$fieldKey]=   $operation[$fieldKey];
                $resValue[$fieldKey]    =   $value[$fieldKey];
            }
        }
        if (!empty($titleWhere))
        {
            $searchSing =   TRUE;
			$programmes[] = CommonUtils::getProgrammeIdsByTitle($titleWhere,$field,$operation);
        }
        if (!empty($pathWhere))
        {
            $searchSing =   TRUE;
			$programmes[] = CommonUtils::getProgrammeIdsByPath($pathWhere);
        }

        if ($searchSing)
        {
			if (count($programmes)>1){
				$programmes = call_user_func_array('array_intersect',$programmes);
			}else{
				$programmes = $programmes[0];
			}
			$programmeTitleIds = implode(',', $programmes);   

            if(empty($programmeTitleIds)) $programmeTitleIds = '""';

            $programmeTitleIds  =   ' WHERE outCast.programme_id IN ('. $programmeTitleIds. ')';
        }

		if($casts){
			if(count($casts)>1){
				$casts = call_user_func_array('array_intersect',$casts);
			}else{
				$casts = $casts[0];
			}
			$where[] = ' id IN(' . implode(',',$casts) . ')';
		}else{
			if($nameSearchSing){
				$where[] = ' 1<>1 ';
			}
		}
		$where[] =	Model::assembleWhereSentence($find, $resField, $resOperation, $resValue);
		$where   = array_filter($where);
		if (!empty($where))
		{
			$where	=	' WHERE '. implode(' and ',$where);
		}else{
			$where  = '';
		}

		$subSql =	'
                SELECT
				    id,
                    programme_id,
				    title,
                    CONCAT(ifnull(real_name_zh,""), "\n\t", ifnull(real_name_en,""))                        AS  real_name,
                    CONCAT(ifnull(cast_name_zh,""), "\n\t", ifnull(cast_name_en,""))                        AS  cast_name,
				    other_name,
				    nickname,
				    record_status,
					modified_at,
				    modified_by
                FROM
                (
				    SELECT DISTINCT
				    	outCast.id														AS	id,
                        outCast.programme_id                                            AS  programme_id,
				    	(
				    		SELECT
				    			GROUP_CONCAT(`p_programme-language`.title SEPARATOR "\n\t")
				    		FROM
				    			`p_cast` AS inCast LEFT JOIN `p_programme-language` ON (inCast.programme_id = `p_programme-language`.programme_id)
				    		WHERE
				    			inCast.id = outCast.id
				    	)																AS	title,
				    	outCast.`status`												AS	record_status,
				    	outCast.modified_by												AS	modified_by,
				    	outCast.modified_at												AS	modified_at,
                        (
                            SELECT
                                CONCAT(`p_cast-language`.real_last_name, " ", `p_cast-language`.real_first_name)
                            FROM
                                `p_cast` AS inCast LEFT JOIN `p_cast-language` ON (`p_cast-language`.cast_id = inCast.id)
                            WHERE
                                `p_cast-language`.language_id = "'. $zhLanguageID. '"
                                AND inCast.id = outCast.id
                        )                                                               AS  real_name_zh,
                        (
                            SELECT
                                CONCAT(`p_cast-language`.real_first_name, " ", `p_cast-language`.real_last_name)
                            FROM
                                `p_cast` AS inCast LEFT JOIN `p_cast-language` ON (`p_cast-language`.cast_id = inCast.id)
                            WHERE
                                `p_cast-language`.language_id = "'. $enLanguageID. '"
                                AND inCast.id = outCast.id
                        )                                                               AS  real_name_en,
                        (
                            SELECT
                                CONCAT(`p_cast-language`.last_name, " ", `p_cast-language`.first_name)
                            FROM
                                `p_cast` AS inCast LEFT JOIN `p_cast-language` ON (`p_cast-language`.cast_id = inCast.id)
                            WHERE
                                `p_cast-language`.language_id = "'. $zhLanguageID. '"
                                AND inCast.id = outCast.id
                        )                                                               AS  cast_name_zh,
                        (
                            SELECT
                                CONCAT(`p_cast-language`.first_name, " ", `p_cast-language`.last_name)
                            FROM
                                `p_cast` AS inCast LEFT JOIN `p_cast-language` ON (`p_cast-language`.cast_id = inCast.id)
                            WHERE
                                `p_cast-language`.language_id = "'. $enLanguageID. '"
                                AND inCast.id = outCast.id
                        )                                                               AS  cast_name_en,
				    	GROUP_CONCAT(`p_cast-language`.other_name SEPARATOR "\n\t")		AS	other_name,
				    	GROUP_CONCAT(`p_cast-language`.nickname SEPARATOR "\n\t")		AS	nickname
				    FROM
				    	`p_cast` AS outCast LEFT JOIN `p_cast-language` ON (outCast.id = `p_cast-language`.cast_id)
                    '. $programmeTitleIds. '
				    GROUP BY id
                )   AS  findTmpApi
				';
		$sql=	'
			SELECT
				id,
                programme_id,
				title,
                real_name,
                cast_name,
				other_name,
				nickname,
				record_status,
				modified_at,
				modified_by
			FROM
			(
				'. $subSql. '
			)	AS	findApi
			'.	$where;

		# Order By ...
		$orderBy=	$orderTmp   =   NULL;
		if (!empty($sidx)	&&	!empty($find[$sidx]))
		{
			$orderTmp	=	$find[$sidx];
			if ('desc'	==	$sord)
			{
				$orderTmp	.=	' DESC ';
			}
			elseif ('asc'	==	$sord)
			{
				$orderTmp	.=	' ASC ';
            }
            $orderBy[]  =   $orderTmp;
		}

        if (!empty($where))
        {
            foreach ($field as  $value)
            {
                if (empty($find[$value]))   continue;
                if ('path' ==  $value)      continue;
                $orderBy[]  =   $find[$value];
            }
        }

        if (empty($orderBy))    $orderBy[]  =   '`findApi`.`modified_at` DESC';

        $orderBy    =   ' ORDER BY '. implode(', ', $orderBy);
		$dataSql	=	$sql. $orderBy. ' LIMIT '. $start. ', '. $length;
		$totalSql	=	'SELECT count(*) AS num FROM ('. $sql. ')	AS	tmp';

		$result	=	$db_con->findBySql(__class__,$dataSql);
		$retAll	=	$db_con->findBySql(__class__,$totalSql);

        if (empty($retAll[0]->num)) $retAll[0]->num =   0;
        if (empty($result[0]))      $result         =   array();
		$list	=	array();
		$list['page']	=	ceil($start / $length) + 1;
		$list['total']	=	ceil($retAll[0]->num / $length);
		$list['records']=	$retAll[0]->num;

		foreach	($result	as	$gridData)
		{
			$tmp			=	array();
			$tmp['id']		=	$gridData->id;
			$tmp['cell']	=	array();
			$gridData->real_name    = explode("\n\t",$gridData->real_name);
			$gridData->real_name[0] = htmlentities($gridData->real_name[0],ENT_QUOTES,'UTF-8');
			$gridData->real_name[1] = isset($gridData->real_name[1]) ? htmlentities($gridData->real_name[1],ENT_QUOTES,'UTF-8') : '';
			$gridData->real_name    = implode('<br />',$gridData->real_name);

			$gridData->cast_name    = explode("\n\t",$gridData->cast_name);
			$gridData->cast_name[0] = htmlentities($gridData->cast_name[0],ENT_QUOTES,'UTF-8');
			$gridData->cast_name[1] = isset($gridData->cast_name[1]) ? htmlentities($gridData->cast_name[1],ENT_QUOTES,'UTF-8') : '';
			$gridData->cast_name    = implode('<br />',$gridData->cast_name);

			$gridData->title    = explode("\n\t",$gridData->title);
			$gridData->title[0] = htmlentities($gridData->title[0],ENT_QUOTES,'UTF-8');
			$gridData->title[1] = isset($gridData->title[1]) ? htmlentities($gridData->title[1],ENT_QUOTES,'UTF-8') : '';
			$gridData->title    = implode('<br />',$gridData->title);

			$gridData->other_name    = explode("\n\t",$gridData->other_name);
			$gridData->other_name[0] = htmlentities($gridData->other_name[0],ENT_QUOTES,'UTF-8');
			$gridData->other_name[1] = isset($gridData->other_name[1]) ? htmlentities($gridData->other_name[1],ENT_QUOTES,'UTF-8') : '';
			$gridData->other_name    = implode('<br />',$gridData->other_name);

			$gridData->nickname    = explode("\n\t",$gridData->nickname);
			$gridData->nickname[0] = htmlentities($gridData->nickname[0],ENT_QUOTES,'UTF-8');
			$gridData->nickname[1] = isset($gridData->nickname[1]) ? htmlentities($gridData->nickname[1],ENT_QUOTES,'UTF-8') : '';
			$gridData->nickname    = implode('<br />',$gridData->nickname);

			$gridData->modified_at= str_replace(' ','<br />',$gridData->modified_at);

            $originalStatus =   $gridData->record_status;
            if (!empty($unpublish))
            {
                //$publish    =   Model::object2array(publish_log::getPublishLog(__class__, $gridData->id));
                $_publish = publish_log::getPublishLog(__class__, $gridData->id);
                $publish    = count((array)$_publish) <= 0 ? array() :  Model::object2array($_publish);
                $publish = isset($publish['premium']) ? $publish['premium'] : array();
                $gridData->record_status    =   NULL;
                $gridData->modified_by      =   NULL;
                $gridData->modified_at      =   NULL;
                if (isset($publish['action'])   &&  isset(AC::$publicLogAction[$publish['action']]))
                {
                    $gridData->record_status    =   AC::$publicLogAction[$publish['action']];
                    isset($publish['published_by']) &&  $gridData->modified_by  =   $publish['published_by'];
                    isset($publish['published_at']) &&  $gridData->modified_at  =   $publish['published_at'];
                }
            }
            else
            {
                isset(AC::$op_status[$gridData->record_status]) &&  $gridData->record_status    =   AC::$op_status[$gridData->record_status];
            }
			foreach ($find	as	$name	=>	$column)
            {
                if('programme_id' == $name || 'path' == $name) continue;
                $tmp['cell'][]	=	$gridData->$name;
			}

            $delEdit    =   $delView    =   NULL;
            if (AC::STATUS_DELETED !=   $originalStatus &&  empty($unpublish))
            {
                $delEdit    =	'<a title="Edit" href="get_cast.html?act=edit&step=2&id='. $gridData->id. '" class="btn edit ui-state-default ui-corner-all"><span class="ui-icon ui-icon-pencil"/>Edit</a>';
            }
            if (empty($unpublish)   ||  (isset($publish['action'])  &&  AC::LOG_OP_PREMIUM_PUBLISH  ==  $publish['action']))
            {
                $delView    =   '<a title="View" href="get_p_cast.html?act=view&step=2&id='. $gridData->id. '&unpublish='. $unpublish. '" class="btn view ui-state-default ui-corner-all"><span class="ui-icon ui-icon-image"/>View</a>';
            }
            $tmp['cell'][]  =   $delEdit. $delView;
			$list['rows'][]	=	$tmp;
            unset($publish);
		}
		return	$list;
	}

    /**
     * get proofread SQL
     * @param   $id Int
     * @return  Array
     */
    public function getProofread($id)
    {
        if (empty($id)) return  array();
		# commented by vanni at 2009-07-11
        #$sqlArr =   array(
        #            'cast'          =>  array('id = "'. $id. '"'),
        #            'cast-language' =>  array('cast_id = "'. $id. '"'),
        #        );

        #$sqlArray   =   NULL;
        #foreach ($sqlArr    as  $tableName  =>  $whereArray)
        #{
        #    $sqlArray[$tableName]   =   Model::assembleGetProofreadSql($tableName, $whereArray);
		#}
		
		# append by vanni at 2009-07-11, comments: Hi Ann，已經刪除的 cast 不應該被 proofread!
		$sqlArray['cast'] ='select * from p_cast where id='.$id.' and status<> '.AC::STATUS_DELETED;
		$sqlArray['cast-language'] = 'select l.* from `p_cast-language` l,`p_cast` c where l.cast_id=c.id and c.id='.$id.' and c.status<>'.AC::STATUS_DELETED;
        return  $sqlArray;
    }
}
?>
